package com.example.app.service

import com.example.app.bean.KL8
import com.example.app.bean.Resp
import com.example.app.dao.KL8Repository
import com.example.app.dao.KLEqualRepository
import com.example.app.util.CalculatePrice
import com.example.app.util.ScheduledTasks
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.*
import org.apache.commons.logging.LogFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.io.IOException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Service
class Api {
    val url = "https://api.jisuapi.com/caipiao/query?appkey=e7d57823e54e4436&caipiaoid=89&issueno="
    val log = LogFactory.getLog(ScheduledTasks::class.java)!!

    @Autowired
    var klRepository: KL8Repository? = null

    @Autowired
    var klEqualRepository: KLEqualRepository? = null

    /**
     * 保存最新的数据
     */
    fun saveNewData() {
        try {
            val client = OkHttpClient()
            val request = Request.Builder().get().url(url).build()
            val call = client.newCall(request)
            call.enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                }

                override fun onResponse(call: Call, response: Response) {
                    val body = response.body?.string()
                    val resultType = object : TypeToken<Resp<KL8>>() {}.type
                    val fromJson = Gson().fromJson<Resp<KL8>>(body, resultType)
                    val result = fromJson.result
                    val kl = KL8()
                    kl.issueno = result.issueno
                    kl.number = result.number
                    kl.opendate = result.opendate!!.substring(0, 10)
                    val no = klRepository!!.findByIssueno(kl.issueno.toString())
                    if (no == null) {
                        klRepository!!.insert(kl)
                        equal(10, kl)
                    }
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 模糊搜索
     */
    fun search(s: String): List<KL8>? {
        val all = klRepository!!.findAll()
        val klList = mutableListOf<KL8>()
        if (s.isEmpty()) {
            return klList
        }
        for (a in all) {
            val c = a.number!!.split(" ").toMutableList()
            val d = s.split(",").toMutableList()
            val b = s.split(",").toMutableList()
            b.retainAll(c)
            if (b.size == d.size) {
                val kl = KL8()
                kl.issueno = a.issueno
                kl.number = a.number
                klList.add(kl)
            }
        }
        return klList
    }

    /**
     * 和之前数据比较出相等数据插入数据库
     */
    fun equal(num: Int, kls: KL8) {
        val all = klRepository!!.findAll()
        val mutableList = kls.number!!.split(" ").toMutableList()
        val klList = mutableListOf<KL8>()
        for (a in all) {
            val b = a.number!!.split(" ").toMutableList()
            b.retainAll(mutableList)
            if (b.size >= num && b.size != 20) {
                val kl = KL8()
                kl.issueno = a.issueno
                kl.after_issueno = kls.issueno
                kl.number = b.toString().replace("[", "").replace("]", "").replace(",", "")
                klList.add(kl)
                if (b.size > 1) {
                    val number = klEqualRepository!!.findByNum(kl.number!!)
                    if (number == null) {
                        klEqualRepository!!.insert(kl)
                        val aa = b.toString()
                        log.info("插入数据：$aa")
                    }
                }
            }
        }

    }

    /**
     * 三连出数据
     */
    fun equalsThree(num: Int): List<KL8>? {
        val all = klEqualRepository!!.findAll()
        val klLists = mutableListOf<KL8>()
        for (index in all[0].id..all[all.size - 1].id) {
            val list = klEqualRepository!!.findById(index.toString())
            val mutableList = list.number!!.split(" ").toMutableList()
            val klList = mutableListOf<KL8>()
            for (a in all) {
                val b = a.number!!.split(" ").toMutableList()
                b.retainAll(mutableList)
                if (b.size >= num && b.size != 20) {
                    val kl = KL8()
                    kl.issueno = list.issueno + "-" + list.after_issueno
                    kl.after_issueno = a.issueno + "-" + a.after_issueno
                    kl.number = a.number
                    if (list.issueno != a.issueno) {
                        klList.add(kl)
                    }
                }
            }
            if (klList.size > 1) {
                klLists.add(klList[0])
            }
        }
        return klLists
    }

    /**
     * 对比出相等号
     */
    fun equalQuery(num: Int): List<KL8>? {
        val all = klEqualRepository!!.findAll()
        val list = mutableListOf<KL8>()
        if (num == 0) {
            return all
        } else {
            for (index in all.size - num..all.size) {
                val kl = KL8()
                kl.issueno = all[index].issueno
                kl.after_issueno = all[index].after_issueno
                kl.number = all[index].number
                list.add(kl)
            }
        }
        return list
    }

    /**
     * 复选10选9号码
     */
    fun checkFs10(): String {
        val all = klRepository!!.findAll()
        val fsList = mutableListOf("02", "09", "30", "35", "45", "50", "65", "66", "73", "76")
        val current = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        var formatted = current.format(formatter)
        var no = klRepository!!.findByOpendate("$formatted 00:00:00")
        if (no != null) {
            val list = no.number!!.split(" ").toMutableList()
            fsList.retainAll(list)
        } else {
            val list = all[all.size - 1].number!!.split(" ").toMutableList()
            fsList.retainAll(list)
            formatted = all[all.size - 1].opendate!!.replace("00:00:00", "")
            no = all[all.size - 1]
        }
        return "快乐8投注号码\n\n复式10选9\n02 09 30 35 45 50 65 66 73 76\n\n" + formatted +
                "开奖号码\n" + no.number +
                "\n\n中奖号码\n" + fsList.toString() +
                "\n\n恭喜中奖\n" + CalculatePrice().calculateFs(fsList.size, 0.9) + "元"
    }

    /**
     * 其他投注
     */
    fun checkOther(): String {
        val all = klRepository!!.findAll()
        val string10_1 = "02 09 30 35 45 50 65 66 73 76"
        val string10_2 = "01 03 04 07 09 12 14 16 18 20"
        val string10_3 = "01 03 04 09 14 15 16 18 20 21"
        val string10_4 = "41 43 44 40 54 55 56 58 60 61"
        val string5_1 = "03 07 10 11 12"
        val string7_1 = "03 07 10 11 12 18 21"
        val list10_1 = string10_1.split(" ").toMutableList()
        val list10_2 = string10_2.split(" ").toMutableList()
        val list10_3 = string10_3.split(" ").toMutableList()
        val list10_4 = string10_4.split(" ").toMutableList()
        val list5_1 = string5_1.split(" ").toMutableList()
        val list7_1 = string7_1.split(" ").toMutableList()
        val current = LocalDateTime.now()
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        var formatted = current.format(formatter)
        var no = klRepository!!.findByOpendate("$formatted 00:00:00")
        var list: List<String>?
        if (no != null) {
            list = no.number!!.split(" ").toMutableList()
        } else {
            list = all[all.size - 1].number!!.split(" ").toMutableList()
            formatted = all[all.size - 1].opendate!!.replace("00:00:00", "")
            no = all[all.size - 1]
        }
        list10_1.retainAll(list)
        list10_2.retainAll(list)
        list10_3.retainAll(list)
        list10_4.retainAll(list)
        list5_1.retainAll(list)
        list7_1.retainAll(list)
        val numString = string10_1 + "\n" + string10_2 + "\n" + string10_3 + "\n" + string10_4 + "\n" + string7_1 + "\n" + string5_1 + "\n\n"
        val price = CalculatePrice().calculate(list10_1.size, 10) +
                CalculatePrice().calculate(list10_2.size, 10) +
                CalculatePrice().calculate(list10_3.size, 10) +
                CalculatePrice().calculate(list10_4.size, 10) +
                CalculatePrice().calculate(list5_1.size, 5) +
                CalculatePrice().calculate(list7_1.size, 7)

        return "快乐8投注号码\n\n" + numString + formatted +
                "开奖号码\n" + no.number +
                "\n\n恭喜中奖\n" + price + "元"
    }

    fun checkZj(s: Int): String {
        val all = klRepository!!.findAll()
        var total = 0
        for (index in 1..s) {
            val list = mutableListOf("02", "09", "30", "35", "45", "50", "65", "66", "73", "76")
            val fsList = all[all.size - index].number!!.split(" ").toMutableList()
            list.retainAll(fsList)
            total += CalculatePrice().calculateFs(list.size, 0.9)
        }
        return "合计金额:$total"
    }
}
